package org.example.controller;


import org.example.Tools.MD5Util;
import org.example.Tools.VerificationCodeUtil;
import org.example.service.UploadService;
import org.example.util.JwtUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.example.service.IUsersService;
import org.example.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 
 * @since 2025-03-27
 */
@Controller
@RestController
@RequestMapping("/user")
public class UsersController {


    @Autowired
    private UploadService uploadService;

    @Autowired
    private IUsersService iUsersService;

    @Autowired
    private JwtUtil jwtUtil;
    //登录
    @PostMapping(value = "/login")
    public Map<String ,Object> login(@RequestBody User usr) {
        Map<String ,Object> loginResponse = new HashMap<>();
        loginResponse.put("code",20201);
        loginResponse.put("message", "登录失败");
        //将密码加密
        usr.setPassword(MD5Util.md5(usr.getPassword()));
        //查询用户信息
        User user = iUsersService.FindUser(usr);
        if(user != null) {
            String token = jwtUtil.generateToken(user.getPhone());
            loginResponse.put("code", 20200);
            loginResponse.put("message", "登录成功");
            loginResponse.put("data", user);
            loginResponse.put("token", token);
        }
        return loginResponse;
    }

    //获取验证码
    @GetMapping(value = "/verificationCode")
    public Map<String ,Object> verificationCode() throws Exception {
        Map<String ,Object> verificationCodeResponse = new HashMap<>();
        //生成验证码
        StringBuilder code = new StringBuilder(4);
        //生成验证码图片
        BufferedImage codeImg=new BufferedImage(100,40,BufferedImage.TYPE_INT_RGB);
        VerificationCodeUtil verifiCodeUtil = new VerificationCodeUtil();
        //将验证码图片返回给前端
        codeImg= verifiCodeUtil.createImage(code);
        // 把 BufferedImage 转为 base64 字符串
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ImageIO.write(codeImg, "png", bos);  // 把图片写入字节流
            byte[] imageBytes = bos.toByteArray();  // 获取字节数组
            String base64Img = Base64.getEncoder().encodeToString(imageBytes);  // 转成 base64 字符串
            bos.close();

            // 前端使用方式：<img :src="'data:image/png;base64,' + codeImg">
            verificationCodeResponse.put("codeImg", "data:image/png;base64," + base64Img);
            verificationCodeResponse.put("verifiCode", code.toString().toLowerCase());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return verificationCodeResponse;
    }
    @GetMapping(value = "/")
    public ResponseEntity<Page<User>> list(@RequestParam(required = false) Integer current, @RequestParam(required = false) Integer pageSize) {
        if (current == null) {
            current = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        Page<User> aPage = iUsersService.page(new Page<>(current, pageSize));
        return new ResponseEntity<>(aPage, HttpStatus.OK);
    }

    @GetMapping(value = "/{id}")
    public ResponseEntity<User> getById(@PathVariable("id") String id) {
        return new ResponseEntity<>(iUsersService.getById(id), HttpStatus.OK);
    }

    //注册
    @PostMapping(value = "/register")
    public Map<String ,Object> register(@RequestBody User usr) {
        Map<String ,Object> registerResponse = new HashMap<>();
        registerResponse.put("code",20201);
        registerResponse.put("message", "注册失败");
        //将密码加密
        usr.setPassword(MD5Util.md5(usr.getPassword()));
        //查询用户信息（判断手机号是否被注册）
        User user = iUsersService.FindUserByPhone(usr.getPhone());
        if(user == null) {
            iUsersService.save(usr);
            registerResponse.put("code", 20200);
            registerResponse.put("message", "注册成功");
            registerResponse.put("data", usr);
        }
        return registerResponse;
    }

    @PostMapping(value = "/delete/{id}")
    public ResponseEntity<Object> delete(@PathVariable("id") String id) {
        iUsersService.removeById(id);
        return new ResponseEntity<>("deleted successfully", HttpStatus.OK);
    }

    @PostMapping(value = "/update")
    public ResponseEntity<Object> delete(@RequestBody User params) {
        iUsersService.updateById(params);
        return new ResponseEntity<>("updated successfully", HttpStatus.OK);
    }
    //修改手机号
    @PostMapping(value = "/updatePhone")
    public Map<String ,Object> updatePhone(@RequestBody User params) {
        Map<String ,Object> registerResponse = new HashMap<>();
        registerResponse.put("code",20201);
        registerResponse.put("message", "修改失败");
        //查询原用户信息
        User user = iUsersService.getById(params.getId());
        //判断用户信息
        if(user != null && user.getPassword().equals(MD5Util.md5(params.getPassword()))){
            iUsersService.setUserPhone(params.getPhone(),params.getId());
            registerResponse.put("code", 20200);
            registerResponse.put("message", "修改成功");
            registerResponse.put("data", params);
        }
        return registerResponse;
    }

    //头像
    @GetMapping("/info")
    public Map<String, Object> getUserInfo() {
        // 模拟数据
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("name", "454544545");
        userInfo.put("phone", "14578985246");
        userInfo.put("avatarUrl", "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png");
        return userInfo;
    }

    //修改头像
    // 接收前端上传文件，主后端再调用子后端接口上传
    @PostMapping("/uploadAvatar")
    public String uploadFileToSubBackend(@RequestParam("file") MultipartFile file) {
        System.out.println(file.getOriginalFilename());
        // 调用业务层上传服务
        return uploadService.uploadFileToSubBackend(file);
    }
}
